package com.itheima.canal.listener;

import com.alibaba.otter.canal.protocol.CanalEntry;
import com.itheima.canal.config.RabbitmqConfig;
import com.xpand.starter.canal.annotation.CanalEventListener;
import com.xpand.starter.canal.annotation.ListenPoint;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.Map;

@CanalEventListener
public class SpuListener {

    //注入RabbitTemplate模板,用于将监听到的消息发送到RabbitMQ交换机上
    @Autowired
    private RabbitTemplate rabbitTemplate;


    @ListenPoint(schema = "changgou_goods", table = "tb_spu")
    public void goodsUp(CanalEntry.EntryType entryType, CanalEntry.RowData rowData) {
        //获取商品上架之前的数据.并将这部分数据转换为map
        Map<String, String> oldData = new HashMap();
        for (CanalEntry.Column column : rowData.getBeforeColumnsList()) {
            oldData.put(column.getName(), column.getValue());
        }

        //获取改变之后的数据,并将这部分数据转换为Map
        Map<String, String> newData = new HashMap<>();
        rowData.getAfterColumnsList().forEach((c) -> newData.put(c.getName(), c.getValue()));


        if ("0".equals(oldData.get("is_marketable")) && "1".equals(newData.get("is_marketable"))) {
            rabbitTemplate.convertAndSend(RabbitmqConfig.GOODS_UP_EXCHANGE, "", newData.get("id"));
        }

        if ("1".equals(oldData.get("is_marketable")) && "0".equals(newData.get("is_marketable"))) {
            rabbitTemplate.convertAndSend(RabbitmqConfig.GOODS_DOWN_EXCHANGE, "", newData.get("id"));
        }
    }
}
